package com.nord.NewsList;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

import com.nord.R;
import com.nord.WebTools.HtmlBrowser;


public class NewsFeed extends Activity {
	
	private Button like, love, submit;
	private EditText message;
	
	private String title, body;
	private int id, likers, lovers;
	private String comment_url, slug;
	private Boolean liked = false, loved = false;
	
	ArrayList<ArrayList<String>> comments;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news_feed);

		Button menuBanner = (Button) findViewById(R.id.menuBanner);
		Typeface tf = Typeface.createFromAsset(getAssets(), "DaysOne-Regular.ttf");
		menuBanner.setTypeface(tf);
		
		like = (Button) findViewById(R.id.like);
		love = (Button) findViewById(R.id.love);
		submit = (Button) findViewById(R.id.submit);
		message = (EditText) findViewById(R.id.message);

		title = getIntent().getExtras().getString("TITLE");
		body = getIntent().getExtras().getString("BODY");
		id = Integer.parseInt(getIntent().getExtras().getString("ID"));
		likers = Integer.parseInt(getIntent().getExtras().getString("LIKERS"));
		lovers = Integer.parseInt(getIntent().getExtras().getString("LOVERS"));
		comment_url = getIntent().getExtras().getString("COMMENTS");
		slug = getIntent().getExtras().getString("SLUG");
		
		if(getIntent().getExtras().getString("LIKED") != null){
			like.setText("Dislæk it (" + String.valueOf(likers) + ")");
			liked = true;
		}
		else
			like.setText("Læk it (" + String.valueOf(likers) + ")");
			
		if(getIntent().getExtras().getString("LOVED") != null){
			love.setText("Önnlöv it (" + String.valueOf(lovers) + ")");
			loved = true;
		}
		else
			love.setText("Löv it (" + String.valueOf(lovers) + ")");
		
		like.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new ExtraNews("like").execute();
			}
		});
		
		love.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new ExtraNews("love").execute();			
			}
		});
		
		submit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String m = message.getText().toString();
				if (m.length() > 0)
					new SubmitComment(m).execute();
				else 
					Toast.makeText(getApplicationContext(), "Hefur þú ekkert að segja ?", Toast.LENGTH_LONG).show();
			}
		});

		new LoadNews().execute();
	}
	
	private class SubmitComment extends AsyncTask<Void,Integer,Boolean>{
		ProgressDialog progressBar;
		String comment;
		
		public SubmitComment(String comment){
			this.comment = comment;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(NewsFeed.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að mixa ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}
		@Override
		protected Boolean doInBackground(Void... v) {
			String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/frettir/"+ id + "/" + slug + "/");
			if(!htmlInfo[0].contains("Exception")){
				String _body = htmlInfo[0].substring(
						htmlInfo[0].indexOf("<input type=\"hidden\" name=\"timestamp"),
						htmlInfo[0].length());
				
				String _timestamp = _body.substring(
						_body.indexOf("value=\"") + 7,
						_body.indexOf("\" id="));

				String _security_hash = _body.substring(
						_body.indexOf("name=\"security_hash\" value=\"") + 28,
						_body.indexOf("\" id=\"id_security_hash\"")
						);
				
				_timestamp = _timestamp.trim();
				_security_hash = _security_hash.trim();
				
				List<Cookie> cookies = ((AbstractHttpClient) HtmlBrowser.httpBrowser)
						.getCookieStore().getCookies();
				
				List<NameValuePair> postParams = new ArrayList<NameValuePair>();
				postParams.add(new BasicNameValuePair("next", "/frettir/" + id + "/" + slug +"/"));
				postParams.add(new BasicNameValuePair("csrfmiddlewaretoken", cookies.get(1).getValue()));
				postParams.add(new BasicNameValuePair("comment", "<p>" + comment + "</p>"));
				postParams.add(new BasicNameValuePair("honeypot", ""));
				postParams.add(new BasicNameValuePair("content_type", "announcements.announcement"));
				postParams.add(new BasicNameValuePair("object_pk", String.valueOf(id)));
				postParams.add(new BasicNameValuePair("timestamp",	_timestamp));
				postParams.add(new BasicNameValuePair("security_hash", _security_hash));
				HtmlBrowser.postExecutor("https://www.nord.is/leikjamot/ath/post/", postParams);
				return true;
			}
			else
				return false;
		}
		
		@Override
		protected void onPostExecute(Boolean b) {
			progressBar.dismiss();
			if(b){
				new LoadNews().execute();
				message.setText("");
			}
			else
				Toast.makeText(getApplicationContext(), "Engin internet tenging.\nGat ekki sent athugasemd", Toast.LENGTH_LONG).show();
		}
	}

	private class ExtraNews extends AsyncTask<Void,Integer,Boolean> {
		
		ProgressDialog progressBar;
		String extra = "";
		
		public ExtraNews(String extra){
			this.extra = extra;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(NewsFeed.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að mixa ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}
		@Override
		protected Boolean doInBackground(Void... v) {
			String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/frettir/"+ id + "/" + slug + "/" +  extra +"/");
			if(!htmlInfo[0].contains("Exception"))
				return true;
			else
				return false;
		}
		
		@Override
		protected void onPostExecute(Boolean status) {
			progressBar.dismiss();
			if(status) {
				if (extra.compareTo("like") == 0){
					if (liked){
						liked = false;
						likers--;
						like.setText("Læk it (" + String.valueOf(likers) + ")");
					}
					else{
						liked = true;
						likers++;
						like.setText("Dislæk it (" + String.valueOf(likers) + ")");
					}
				}
				if (extra.compareTo("love") == 0){
					if (loved){
						loved = false;
						lovers--;
						love.setText("Löv it (" + String.valueOf(lovers) + ")");
					}
					else{
						loved = true;
						lovers++;
						love.setText("Önnlöv it (" + String.valueOf(lovers) + ")");
					}
				}
			}
			else
				Toast.makeText(getApplicationContext(), "Engin internet tenging.\nGat ekki uppfært", Toast.LENGTH_LONG).show();
		}
	}
	
	private class LoadNews extends AsyncTask<Void, Integer, Void> {
		ProgressDialog progressBar;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(NewsFeed.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að færa fréttina ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();

		}
		
		@Override
		protected Void doInBackground(Void... params) {
				String tmp = "<h1>" + title + "</h1>";
				tmp += body;
				body = tmp;
				
				String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/"+comment_url);
				if(!htmlInfo[0].contains("Exception")){
					comments = HtmlBrowser.jsonNewsCommentProcessor(body, String.valueOf(id) , htmlInfo[0]);
					body += "<hr>";
					body += "<b><h3>Athugasemdir</h3></b>";
					for(int i = 0; i < comments.size();i++){
						for(int j = 0;j < comments.get(i).size();j++){
							if(j != 0 )
								body += "<font color=\"gray\" size=\"2\">";
							if(j == 2 )
								body += " - ";
							body += comments.get(i).get(j);
							body += "</font>";
						}
						if(i != comments.size()-1)
							body += "<hr>";
					}
				}
				return null;
		}
		@Override
		protected void onPostExecute(Void v) {
			progressBar.dismiss();
			try {
				WebView webview = (WebView) findViewById(R.id.webView1);
				webview.loadDataWithBaseURL(null, body, "text/html", "utf-8", null);
				webview.setBackgroundColor(0x00000000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
